<template>
  <div>
    <!-- 头部导航 -->
    <div
      style="
        background: linear-gradient(to bottom, #fe7f2d, #ffc6a0, #f3f8fa);
        padding-left: 10px;
        padding-right: 10px;
        padding-bottom: 10px;
        border-radius: 0px 0px 10px 10px;
      "
    >
      <div
        style="
          display: flex;
          justify-content: space-between;
          padding-top: 1.25rem;
          color: white;
        "
      >
        <div style="font-size: 18px">
          <van-icon name="arrow-left" />
          <span>1小时达</span>
        </div>
        <div
          style="
            background: rgba(255, 255, 255, 0.2);
            padding: 5px;
            border-radius: 10px;
            font-size: 8px;
          "
        >
          已订阅
        </div>
        <div style="cursor: pointer" @click="router.push('/city')">
          {{ city }}
        </div>
      </div>
      <!-- 搜索框 -->
      <van-search
        v-model="keywords"
        show-action
        shape="round"
        background="rgba(254, 127, 45,0.0)"
        placeholder="搜索"
        style="position: relative"
      >
        <template #action>
          <div
            style="
              position: absolute;
              right: 16px;
              bottom: 10px;
              background: #fd761a;
              padding: 0px 13px;
              border-radius: 999px;
              color: white;
              font-size: 14px;
            "
            @click="doSearch"
          >
            搜索
          </div>
        </template>
      </van-search>
      <!-- 通知栏 -->
      <van-notice-bar
        left-icon="volume-o"
        text="全场大降价，全网比价，买贵包赔!"
        :scrollable="true"
      />
      <!-- 轮播图 -->
      <van-swipe :autoplay="3000" lazy-render>
        <van-swipe-item v-for="item in data.banners" :key="item.id">
          <img :src="item.picUrl" class="a" />
        </van-swipe-item>
      </van-swipe>
      <!-- 分类 -->
      <!-- 分类 gird 宫格布局 -->
      <div style="background-color: white">
        <van-grid :border="false" :column-num="5" style="margin-top: 10px">
          <van-grid-item
            v-for="item in category"
            :key="item.title"
            @click="changeCate(item.title)"
          >
            <van-image :src="item.pic" />
            <div style="font-size: 2.93333vw">{{ item.title }}</div>
          </van-grid-item>
        </van-grid>
      </div>
    </div>
    <!-- tab栏 -->
    <van-tabs
      v-model:active="active"
      title-active-color="#36d321"
      color="#36d321"
      sticky
    >
      <van-tab :title="item1" v-for="item1 in tabs">
        <div style="display: flex; overflow-x: scroll">
          <div class="item" v-for="item in data.goods" :key="item.id">
            <!-- 图片 -->
            <div>
              <img :src="item.pic" alt="" />
            </div>
            <div>
              <!-- 商品名称 -->
              <div class="van-ellipsis">{{ item.name }}</div>
              <!-- tip提示 -->
              <div>
                本周热卖
                <span style="color: red; font-weight: bold">{{
                  item.buyCount
                }}</span>
              </div>
            </div>
            <div>
              <div>¥{{ item.price }}</div>
              <div>
                <van-icon name="cart-o" @click="addCart(item)" />
              </div>
            </div>
          </div>
        </div>
      </van-tab>
    </van-tabs>
    <!-- 商品列表 -->
    <!-- 分页 -->
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :immediate-check="false"
    >
      <div
        style="
          display: flex;
          flex-wrap: wrap;
          margin-top: 10px;
          padding-left: 2px;
          padding-right: 2px;
        "
      >
        <div class="item1" v-for="item in data.goodsList" :key="item.name">
          <div>
            <img class="c" :src="item.pic" />
          </div>
          <div>
            <div class="van-multi-ellipsis--l2">{{ item.name }}</div>
            <!-- <div>{{ item. }}</div> -->
          </div>
          <div>
            <div>
              ¥ <span>{{ item.price }}</span>
            </div>
            <div>
              <van-icon name="cart-o" @click="addCart(item)" />
            </div>
          </div>
        </div>
      </div>
    </van-list>
    <!-- 回到顶部 -->
    <!-- 组件 -->
    <van-back-top bottom="80px" style="background-color: #fe7f2d" />
  </div>
</template>

<script setup lang="ts">
import req from "@/utils/req";
import { reactive, ref } from "vue";
//userRouter 相当于Vue2中 this.$router 导入之后可全局使用push(),replace(),go()等方法
import { useRouter } from "vue-router";
import { showConfirmDialog, Toast } from "vant";
import type { Ref } from "vue";
// js里面使用图片  需要import导入
import icon1 from "../assets/image/grid/01.png";
import icon2 from "../assets/image/grid/02.png";
import icon3 from "../assets/image/grid/03.png";
import icon4 from "../assets/image/grid/04.png";
import icon5 from "../assets/image/grid/05.png";
import icon6 from "../assets/image/grid/06.png";
import icon7 from "../assets/image/grid/07.png";
import icon8 from "../assets/image/grid/08.png";
import icon9 from "../assets/image/grid/09.png";
import icon10 from "../assets/image/grid/10.png";
import { showToast } from "vant";
import { templateElement } from "@babel/types";
import { useCartStore } from '@/stores/cart'
const storeCart = useCartStore()


loadBanner();
const router = useRouter();
//搜索关键字
const keywords = ref("");
//处理红线问题， ts严格规定 没有定义类型就报错
//方法一： 定义类型为any任意类型，只定义了一层banners，banner下一层没有定义
interface Data {
  goodsList: any;
  goods: any;
  banners: any;
}
//方法二： 数据类型多的时候，可以用此方式，在此处，方法二不能用
// interface Data {
//   banners: Banner
// }
// interface Banner {
//   id: number
//   name: string
//   picUrl: string
// }

//Data是给对像做类型的，自定义类型
const data: Data = reactive({
  banners: [],
  goods: [],
  goodsList: [],
  cartList:[],
});
//加载轮播图数据
function loadBanner() {
  req.get("http://localhost:3000/banner").then((res) => {
    console.log(res);
    data.banners = res.data;
  });
}
//搜索商品
const doSearch = () => {
  router.push("/search?keywords=" + keywords.value);
};

// 定位城市
const city: Ref<string | null> = ref("");
// const BMapGL: any = null
// 判断上次定位的时间
const exp = localStorage.getItem("city_exp")
  ? Number(localStorage.getItem("city_exp"))
  : 0;
// 有缓存显示缓存城市
if (
  localStorage.getItem("city") &&
  new Date().getTime() - exp < 1000 * 3600 * 12
) {
  city.value = localStorage.getItem("city");
} else {
  showConfirmDialog({
    title: "城市定位",
    message: "本应用需要获取使用的地理城市信息,是否同意?",
  })
    .then(() => {
      // on confirm
      var localcity = new BMapGL.LocalCity();
      localcity.get((e: any) => {
        console.log(e);
        city.value = e.name;
        localStorage.setItem("city", e.name);
        //设置时间戳  exprire到期 => exp
        localStorage.setItem("city_exp", String(new Date().getTime()));
      });
    })
    .catch(() => {
      // on cancel
      router.push("/city");
    });
}
// 分类
let category = reactive([
  { title: "热销爆款", pic: icon1 },
  { title: "新鲜果蔬", pic: icon2 },
  { title: "肉蛋水产", pic: icon3 },
  { title: "乳品烘焙", pic: icon4 },
  { title: "素食熟食", pic: icon5 },
  { title: "粮油调味", pic: icon6 },
  { title: "休闲零食", pic: icon7 },
  { title: "酒水饮料", pic: icon8 },
  { title: "个护清洁", pic: icon9 },
  { title: "母婴百货", pic: icon10 },
]);
const changeCate = (e: any) => {
  showToast(e + "正在开发");
};
//tab栏
const active = ref(0);
let tabs: any = reactive([
  "推荐",
  "世界杯",
  "水果",
  "肉禽蛋",
  "烘焙",
  "冰品",
  "蔬菜",
  "零食",
  "饮料",
]);
const loadTabsData = () => {
  req.get("http://localhost:3000/goods").then((res) => {
    console.log(res);
    data.goods = res.data;
  });
};
loadTabsData();
// const changeTab = (e) => {
//   console.log(e);
//   loadTabsData(e.name);
// };
const next_page = ref(1);
//获取商品列表数据
const loadGoodsData = (page = 1) => {
  req.get(`http://localhost:3000/goods?_page=${page}&_limit=6`).then((res) => {
    console.log(res);
    // 将获取回来的分页数据 进行和原来数据的拼接
    // data.goodsList = res.data
    data.goodsList = [...data.goodsList, ...res.data];
    // 加载状态结束
    loading.value = false;
    // 如果next_page 大于4 就没有数据了  finished状态为true
    if (next_page.value >= Math.ceil(res.headers["x-total-count"] / 6)) {
      finished.value = true;
    }
    // 页数加1
    next_page.value += 1;
  });
};
loadGoodsData();
//商品列表分页
const loading = ref(false);
const finished = ref(false);
const onLoad = () => {
  loadGoodsData(next_page.value);
};
//添加购物车
const addCart = (item: any) => {
  //解决销量和购物车的购买量一样的问题
  //解决方法： 深拷贝 Object.assign(目标对象，原对象)
  const tmp: any = {};

  Object.assign(tmp, item);

  tmp.buyCount = 1;
  req.post("http://localhost:3000/cartList", tmp).then((res) => {
    if (res) {
      showToast({
        message: "添加商品成功",
        icon: "cart",
      });
       // 操作store存储购物车的数据  添加数据
       storeCart.cartList.push(res.data)
    }
  });
//此处可改进判断购物车重复添加报错问题

};
</script>

<style lang="scss" scoped>
.van-notice-bar {
  height: 30px;
  border-radius: 10px;
}
.van-swipe-item {
  height: 120px;
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 10px;
}
.a {
  width: 100%;
  height: 100%;
}
.item {
  width: 33%;

  padding: 10px;

  img {
    width: 100%;
  }

  > div:nth-child(2) {
    > div:nth-child(1) {
      font-size: 14px;
      font-weight: bold;
    }

    > div:nth-child(2) {
      font-size: 12px;
      color: gold;
    }
  }

  > div:nth-child(3) {
    display: flex;
    justify-content: space-between;

    > div:nth-child(1) {
      color: red;
      padding-left: 2px;
    }

    > div:nth-child(2) {
      margin-right: 5px;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 20px;
      height: 20px;
      padding: 2px;
      background-color: #36d321;
      color: white;
      border-radius: 50%;
    }
  }
}
.item1 {
  width: 45%;
  padding: 6px;
  margin-bottom: 10px;
  margin-left: 5px;
  background-color: white;
  border-radius: 10px;

  > div:nth-child(2) {
    > div:nth-child(1) {
      font-size: 14px;
      font-weight: bold;
    }

    > div:nth-child(2) {
      font-size: 13px;
      color: gold;
    }
  }

  > div:nth-child(3) {
    display: flex;
    justify-content: space-between;

    > div:nth-child(1) {
      color: red;
      padding-left: 2px;

      > span:nth-child(1) {
        font-size: 18px;
      }
    }

    > div:nth-child(2) {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 20px;
      height: 20px;
      padding: 2px;
      background-color: #36d321;
      color: white;
      border-radius: 50%;
    }
  }
}
.c {
  width: 100%;
}
::v-deep(.van-tabs__wrap) {
  font-weight: bold;
}
::v-deep(.van-tabs__nav) {
  > div:nth-child(2) {
    color: red;
  }
}
::v-deep(.van-list__finished-text) {
  padding-top: 50px;
}
.van-button:before {
  border: none;
}
// }
</style>
